﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using Curling.CurlingServer;

namespace Curling
{
    [DataContractAttribute]
    public class StoneReplay
    {
        [DataMemberAttribute]
        public List<StoneReplayFrame> StoneReplayFrames;

        [DataMemberAttribute]
        public StoneColor Color { get; set; }

        [DataMemberAttribute]
        public int CurrentFrame { get; set; }

        public StoneReplay(StoneEntity stone)
        {
            StoneReplayFrames = new List<StoneReplayFrame>();

            StoneReplayFrames.Add(new StoneReplayFrame()
            {
                X = stone.X,
                Y = stone.Y,
                Rotation = stone.Rotation,
                Velocity = Math.Sqrt(stone.VelocityX * stone.VelocityX + stone.VelocityY * stone.VelocityY),
                State = stone.State,
                TimeStamp = TimeSpan.FromSeconds(0)
            });

            Color = stone.stoneColor;            

            CurrentFrame = 0;
        }

        public StoneReplayFrame AddFrame(Stone stone, TimeSpan GameTime)
        {
            int LastIndex = StoneReplayFrames.Count - 1;

            if (stone.stoneEntity.X != StoneReplayFrames[LastIndex].X || stone.stoneEntity.Y != StoneReplayFrames[LastIndex].Y || stone.stoneEntity.Rotation != StoneReplayFrames[LastIndex].Rotation || stone.stoneEntity.State != StoneReplayFrames[LastIndex].State)
            {
                StoneReplayFrame stoneReplayFrame = new StoneReplayFrame() { X = stone.stoneEntity.X, Y = stone.stoneEntity.Y, Rotation = stone.stoneEntity.Rotation, State = stone.stoneEntity.State, Velocity = Math.Sqrt(stone.stoneEntity.VelocityX * stone.stoneEntity.VelocityX + stone.stoneEntity.VelocityY * stone.stoneEntity.VelocityY), TimeStamp = GameTime };

                StoneReplayFrames.Add(stoneReplayFrame);

                return stoneReplayFrame;
            }

            return null;
        }

        public StoneReplayFrame GetFrame(TimeSpan ReplayTime)
        {
            for (int i = CurrentFrame; i < StoneReplayFrames.Count; i++)
            {
                if (ReplayTime.CompareTo(StoneReplayFrames[i].TimeStamp) < 0)
                {
                    CurrentFrame = i;
                    return StoneReplayFrames[i - 1];
                }
            }

            return StoneReplayFrames[StoneReplayFrames.Count - 1];
        }

        public StoneReplayFrame GetLastFrame()
        {
            return StoneReplayFrames[StoneReplayFrames.Count - 1];
        }
    }
}
